package log;

import java.text.SimpleDateFormat;

import javax.swing.JTextArea;

import org.slf4j.Logger;

import Entity.WcsDvcEntity;
import utils.GlobalOjbectUnits;
import window.WcsWindow;

public class WcsLog {
	private static WcsWindow wcsWindow = GlobalOjbectUnits.getWindow();
	
	private WcsDvcEntity wcsDvcEntity;
	private Logger sourceLogger;
	
	public WcsLog(Logger sourceLogger, WcsDvcEntity wcsDvcEntity) {
		this.sourceLogger = sourceLogger;
		this.wcsDvcEntity = wcsDvcEntity;
		System.out.println(this.wcsDvcEntity.getDvcDesc());
	}
	
	public WcsLog(Logger sourceLogger) {
		this.sourceLogger = sourceLogger;
	}
	
	
	
	
	/**
	 * 面向单个plc连接的日志，会打印出带有dvcNo的日志。
	 * 日志级别中info及以上的日志，分别在控制台、java视图、日志文件中输出
	 */
	public void info(String msg) {
		printView(msg);
		boolean isSelected = wcsWindow.getChkLog().isSelected();
		if (isSelected) {
			sourceLogger.info(msg);
		}
	}
	
	/**
	 * 面向单个plc连接的日志，会打印出带有dvcNo的日志。
	 * 日志级别中info及以上的日志，分别在控制台、java视图、日志文件中输出
	 */
	public void error(String msg) {
		printView(msg);
		boolean isSelected = wcsWindow.getChkLog().isSelected();
		if (isSelected) {
			sourceLogger.error(msg);
		}
	}
	/**
	 * 打印到java可视化界面
	 * @param msg
	 */
	private void printView(String msg) {
		JTextArea textArea = wcsWindow.getTextArea();
		String dvcNo;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String format = null;
		if (wcsDvcEntity == null) {
			dvcNo = "空";
	        format = String.format("%s [%s] %s\n", 
	        		formatter.format(System.currentTimeMillis()),
					Thread.currentThread().getName(),
					msg);
		}else {
			dvcNo = wcsDvcEntity.getDvcNo();
	        format = String.format("%s [%s] [dvc_no:%s] %s\n", 
	        		formatter.format(System.currentTimeMillis()),
					Thread.currentThread().getName(),
					dvcNo,
					msg);
		}
        if (textArea.getLineCount() > 5000)
        {
            textArea.setText("");
        }


        textArea.append(format);
//        textArea.append(formatter.format(System.currentTimeMillis()) + "    ["
//                + Thread.currentThread().getName() + "]" +"    ["+"008"+"]    " + msg
//                + "\r\n");
	}
}
